package org.mijia.dotsbox;

import java.io.File;

import org.eclipse.core.runtime.Platform;
import org.mijia.dotsbox.core.FolderDao;
import org.mijia.dotsbox.core.ChannelDao;
import org.mijia.dotsbox.core.Profile;
import org.mijia.dotsbox.core.model.Folder;
import org.mijia.dotsbox.core.model.Channel;
import org.mijia.dotsbox.rcp.DotsboxActivator;
import org.mijia.dotsbox.utils.LogUtils;

public class DotsboxApp {

	static class DotsboxAppHolder {
		static DotsboxApp instance = new DotsboxApp();
	}
	
	private boolean initialized;
	
	private final File metaDir;
    private final File userDir;
    
	private DotsboxApp() {	
		metaDir = new File(DotsboxActivator.getDefault().getStateLocation().toOSString());
        userDir = Platform.getLocation().toFile();
	}
	
	public static DotsboxApp getInstance() {
		return DotsboxAppHolder.instance;
	}
	
	public static final String ROOT_FOLDER_ID = "__root_folder__";
	
	// manage and initialize all the components
	private Profile profile;
	private Folder rootFolder;
	private TaskDispatcher taskDispatcher;
	
	public void initInstance() {
		if (initialized)
			return;
		
		LogUtils.info("<!-- Initializing DotsboxApp-->");
		
		if (profile == null) {
			profile = new Profile(userDir);
			profile.bindDao(new FolderDao(), Folder.class);
			profile.bindDao(new ChannelDao(), Channel.class);
		}
		
		if (taskDispatcher == null) {
			taskDispatcher = new TaskDispatcher();
		}
		
		initialized = true;
	}
	
	public void dispose() {
		if (taskDispatcher != null) {
			taskDispatcher.dispose();
			taskDispatcher = null;
		}
		
		if (profile != null) {
			profile.dispose();
			profile = null;
		}
		
		DotsboxAppGui.getInstance().dispose();
		initialized = false;
		LogUtils.info("<!-- DotboxApp disposed -->");
	}
	
	public TaskDispatcher getTaskDispatcher() {
		return taskDispatcher;
	}
	
	public Profile getProfile() {
		return profile;
	}
	
	public synchronized Folder getRootFolder() {
		if (rootFolder == null) {
			FolderDao fdao = (FolderDao) profile.getDao(Folder.class);
			assert (fdao != null);
			rootFolder = fdao.find(ROOT_FOLDER_ID);
			if (rootFolder == null) {
				rootFolder = new Folder();
				rootFolder.setId(ROOT_FOLDER_ID);
				rootFolder.setName(ROOT_FOLDER_ID);
				fdao.save(rootFolder);
			}
		}
		return rootFolder;
	}
}